package mh.demo.restful.controller;

import mh.demo.restful.exception.UserNotFoundException;
import mh.demo.restful.model.User;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/users")
public class UserController {

    private final Map<Long, User> usersMap = new HashMap<>();
    private final AtomicLong idGenerator = new AtomicLong();

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        if (usersMap.containsKey(id)) {
            return ResponseEntity.ok(usersMap.get(id));
        }
        throw new UserNotFoundException("没发现ID是" + id + "的用户");
    }

    @PostMapping("/")
    public ResponseEntity<User> createUser(@RequestBody User user) {
        user.setId(idGenerator.incrementAndGet());
        usersMap.put(user.getId(), user);
        return ResponseEntity.ok(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        if (usersMap.containsKey(id) && usersMap.remove(id) != null) {
            return ResponseEntity.noContent().build(); // 204 No Content
        } else {
            throw new UserNotFoundException("没发现ID是" + id + "的用户");
        }
    }

}